package com.app.utils;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

public class HttpClients {
    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;
    private static final int MAX_TIMEOUT = 30000;

    public static String doPost(final String apiUrl, final Map<String, Object> params) throws Exception {
        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        String httpStr = null;
        CloseableHttpResponse response = null;
        try {
            final HttpPost httpPost = new HttpPost(apiUrl);
            httpPost.setConfig(HttpClients.requestConfig);
            final List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
            for (final Map.Entry<String, Object> entry : params.entrySet()) {
                final NameValuePair pair = (NameValuePair) new BasicNameValuePair((String) entry.getKey(), entry.getValue().toString());
                pairList.add(pair);
            }
            httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity((Iterable) pairList, Charset.forName("UTF-8")));
            response = httpClient.execute((HttpUriRequest) httpPost);
            System.out.println(response.toString());
            final HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
            System.out.println(httpStr);
        } catch (IOException e) {
            e.printStackTrace();
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException f) {
                    f.printStackTrace();
                }
            }
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        }
        return httpStr;
    }

    public static String doGet(final String url) {
        return doGet(url, new HashMap<String, Object>());
    }

    public static String doGet(final String url, final Map<String, Object> params) {
        final StringBuffer param = new StringBuffer();
        String httpStr = null;
        int i = 0;
        for (final String key : params.keySet()) {
            if (i == 0) {
                param.append("?");
            } else {
                param.append("&");
            }
            param.append(key).append("=").append(params.get(key));
            ++i;
        }
        final String apiUrl = url + (Object) param;
        final HttpClient httpclient = (HttpClient) org.apache.http.impl.client.HttpClients.createDefault();
        try {
            final HttpGet httpPost = new HttpGet(apiUrl);
            final HttpResponse response = httpclient.execute((HttpUriRequest) httpPost);
            final int statusCode = response.getStatusLine().getStatusCode();
            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                entity.getContent();
                httpStr = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpStr;
    }

   /* public static String doPost(final String apiUrl, Map<String, String> map) throws Exception {
        return  doPost(apiUrl, new HashMap<String, Object>());
    }*/


    public static String requestTokenPost(final String url) {
        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        String httpStr = "";
        try {
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    public static String requestPost(final String url, String requestJson) {

        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = null;
        String httpStr = "";
        try {
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPost Execute Error:" + e);
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + f);
            }
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPost Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    public static String requestPut(final String url, String requestJson) {

        final CloseableHttpClient httpClient = org.apache.http.impl.client.HttpClients.createDefault();
        final HttpUriRequest httpPut = new HttpPut(url);
        HttpEntity entity = null;
        String httpStr = "";
        try {
            httpPut.addHeader("Content-type", "application/json; charset=utf-8");
            entity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
            ((HttpPut) httpPut).setEntity(entity);
            CloseableHttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPut);
            final HttpEntity responseEntity = httpResponse.getEntity();
            httpStr = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            System.out.println("HttpClient requestPut Execute Error:" + e);
            ((HttpPut) httpPut).releaseConnection();
            try {
                httpClient.close();
            } catch (IOException f) {
                System.out.println("HttpClient requestPut Close httpClient Error:" + f);
            }
        } finally {
            ((HttpPut) httpPut).releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e2) {
                System.out.println("HttpClient requestPut Close httpClient Error:" + e2);
            }
        }
        return httpStr;
    }

    static {
        (HttpClients.connMgr = new PoolingHttpClientConnectionManager()).setMaxTotal(100);
        HttpClients.connMgr.setDefaultMaxPerRoute(HttpClients.connMgr.getMaxTotal());
        final RequestConfig.Builder configBuilder = RequestConfig.custom();
        configBuilder.setConnectTimeout(30000);
        configBuilder.setSocketTimeout(30000);
        configBuilder.setConnectionRequestTimeout(30000);
        HttpClients.requestConfig = configBuilder.build();
    }
}
